package edu.qust.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.qust.domain.Book;
import edu.qust.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping("/index")
    public ModelAndView index(Book book, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        ModelAndView mav = new ModelAndView("index");
        List<Book> bookList = bookService.findAllBook(book);
        PageInfo<Book> pageInfo = new PageInfo<>(bookList);
        mav.addObject(pageInfo);
        System.out.println(mav + ".......");
        return mav;
    }

    @RequestMapping("/deleteBok")
    public @ResponseBody
    JSONObject deleteBook(@RequestParam(value = "id", defaultValue = "") Integer id) {
        Integer result = bookService.deleteBook(id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return jsonObject;
    }

    @RequestMapping("/editBok/{id}")
    public @ResponseBody JSONObject editBok(@PathVariable("id") Integer id) {
        Book bok = new Book();
        bok.setBid(id);
        Book b = bookService.selectBook(bok);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("book",b);
        return jsonObject;
    }

    @RequestMapping("/doEditBok")
    public @ResponseBody
    JSONObject doEditBok(Book book) {
        JSONObject json = new JSONObject();
        if (bookService.editBook(book) > 0) {
            json.put("res", "success");
        } else {
            json.put("res", "fail");
        }
        return json;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute("loginbok");
        return "login";
    }

    @RequestMapping("/addBook")
    public String addBook(){

        return "bokadd";
    }
    @RequestMapping("/doAddBok")
    public @ResponseBody JSONObject doAddBok(Book book){
        JSONObject jsonObject =new JSONObject();
        Book bok=new Book();
        bok.setBnum(book.getBnum());
        System.out.println(bok);
        if (bookService.selectBook(bok)!=null){
            jsonObject.put("res","had");
        }else {
            if (bookService.addBook(book)>0){
                jsonObject.put("res","success");
            }else {
                jsonObject.put("res","fail");
            }
        }
        return jsonObject;
    }

}
